package com.dongjiantong.farmrecords.serviceImpl;

import com.alibaba.dubbo.config.annotation.Service;
import com.dongjiantong.common.exceptions.HttpCode;
import com.dongjiantong.common.exceptions.OPServerException;
import com.dongjiantong.common.utils.ReportNumberMakerUtil;
import com.dongjiantong.common.web.sso.LoginInfo;
import com.dongjiantong.farmrecords.enums.FarmRecordsFileEnum;
import com.dongjiantong.farmrecords.enums.FarmRecordsNumberStatus;
import com.dongjiantong.farmrecords.mapper.FarmRecordsFileMapper;
import com.dongjiantong.farmrecords.mapper.FarmRecordsPurchaseMapper;
import com.dongjiantong.farmrecords.model.FarmRecordsFile;
import com.dongjiantong.farmrecords.model.FarmRecordsPurchase;
import com.dongjiantong.farmrecords.service.FarmRecordsFileService;
import com.dongjiantong.farmrecords.service.FarmRecordsPurchaseService;
import com.dongjiantong.mybatis.ServiceMybatis;
import com.dongjiantong.user.enums.FarmsEnum;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.zookeeper.Op;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 采购中心-养殖场采购记录
 */
@Slf4j
@Service(version = "1.0.0")
public class FarmRecordsPurchaseServiceImpl extends ServiceMybatis<FarmRecordsPurchase> implements FarmRecordsPurchaseService {

    @Resource
    private FarmRecordsPurchaseMapper farmRecordsPurchaseMapper;
    @Resource
    private FarmRecordsFileMapper farmRecordsFileMapper;

    @Resource
    private FarmRecordsFileService farmRecordsFileService;

    @Override
    public PageInfo<FarmRecordsPurchase> selectByMap(Integer pageNum, Integer pageSize, Map map) {
        try {
            if (farmRecordsPurchaseMapper == null){
                throw new OPServerException("farmRecordsPurchaseMapper 为null,请检查");
            }
            PageHelper.startPage(pageNum,pageSize);
            //查询有效单据
            map.put("delete_flag", FarmRecordsNumberStatus.EFFECTIVE.getCode());
            //查询已启用的养殖场
            map.put("farmStatus", FarmsEnum.status_true.getCode());
            List<FarmRecordsPurchase> farmRecordsPurchaseList = farmRecordsPurchaseMapper.selectByMap(map);

            Integer type = (Integer) map.get("type");
            return new PageInfo<FarmRecordsPurchase>(farmRecordsPurchaseList);
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new OPServerException(e.getMessage());
        }
    }

    /**
     * 新建一条记录 (暂存状态下)
     * @param farmRecordsPurchase
     * @param toStatus
     * @return  long 返回插入数据的id
     */
    @Override
    public Long createOne(LoginInfo loginInfo,FarmRecordsPurchase farmRecordsPurchase, Integer toStatus) {
        if (farmRecordsPurchaseMapper == null){
            throw new OPServerException("farmRecordsPurchaseMapper 为null,请检查");
        }
        Integer type = farmRecordsPurchase.getType();
        if (type == null){
            throw new OPServerException(HttpCode.BAD_REQUEST,"购置类型不能为空,请检查购置类型");
        }
        try {
            Integer fromStatus = farmRecordsPurchase.getStatus();

            //todo 生成单据号
            //单据生成规则暂未定(此处为测试)
            String prefix = null;

            if (type == 1){
                prefix = "CYL";
            }else if (type == 2){
                prefix = "CYW";
            }else if (type == 3){
                prefix = "CYM";
            }else {
                prefix = "CQT";
            }
            prefix = ReportNumberMakerUtil.createPrefix(prefix,loginInfo.getProvinceId(),loginInfo.getCityId(),loginInfo.getRegionId());
            String maxNumber = farmRecordsPurchaseMapper.findMaxNumber(prefix);
            String number = ReportNumberMakerUtil.create(prefix,maxNumber);
            farmRecordsPurchase.setNumber(number);

            farmRecordsPurchase.setProvince_id(loginInfo.getProvinceId());
            farmRecordsPurchase.setCity_id(loginInfo.getCityId());
            farmRecordsPurchase.setRegion_id(loginInfo.getRegionId());
            farmRecordsPurchase.setStreet_id(loginInfo.getStreetId());
            farmRecordsPurchase.setVillage_id(loginInfo.getVillageId());

            farmRecordsPurchase.setDelete_flag(FarmRecordsNumberStatus.EFFECTIVE.getCode());

            //todo 单据从状态到状态
            if (fromStatus == 0 && toStatus == null) {
                //直接暂存
                farmRecordsPurchaseMapper.createOne(farmRecordsPurchase);
            }else if (!fromStatus.equals(toStatus) && FarmRecordsNumberStatus.SUBMIT.getCode().equals(toStatus)) {
                //直接提交
                farmRecordsPurchase.setStatus(toStatus);
                farmRecordsPurchaseMapper.createOne(farmRecordsPurchase);

            }

            //todo 生成政府操作记录

            return farmRecordsPurchase.getId();
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new OPServerException(HttpCode.DATA_CREATE_FAIL,HttpCode.DATA_CREATE_FAIL.getMessage());
        }
    }

    /**
     * 更新一条记录 (根据id或者number)
     * @param farmRecordsPurchase
     * @return  boolean (更新成功返回true 反之返回false)
     */
    @Override
    public Integer updateByIdOrNumber(FarmRecordsPurchase farmRecordsPurchase,Integer toStatus) {
        try {
            if (farmRecordsPurchaseMapper == null){
                throw new OPServerException("farmRecordsPurchaseMapper 为null,请检查");
            }

            farmRecordsPurchase.setStatus(toStatus);
            farmRecordsPurchase.setUpdated_at(new Date());

            int con = farmRecordsPurchaseMapper.updateByPrimaryKeySelective(farmRecordsPurchase);
            return con;
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new OPServerException(HttpCode.DATA_UPDATE_FAIL,HttpCode.DATA_UPDATE_FAIL.getMessage());
        }
    }

    @Override
    public PageInfo<FarmRecordsPurchase> selectListByStatus(Integer pageNum, Integer pageSize, Integer status, Long farmId,Integer type) {
        PageHelper.startPage(pageNum,pageSize);

        Map<String,Object> map = Maps.newHashMap();

        if (status != null) {
            map.put("status",status);
        }

        map.put("farm_id",farmId);
        map.put("delete_flag",FarmRecordsNumberStatus.EFFECTIVE.getCode());
        if (type != null) {
            map.put("type",type);
        }

        List<FarmRecordsPurchase> farmRecordsPurchaseList = farmRecordsPurchaseMapper.selectListByStatus(map);

        return new PageInfo<FarmRecordsPurchase>(farmRecordsPurchaseList);
    }

    /**
     * 根据养殖场id 时间区间和购置类型获取总数量和总价格
     * */
    @Override
    public Map<String, Object> selectQuantityAndPrice(Long farmId, Integer type, Date startDate, Date endDate) {
        if (type == null) {
            throw new OPServerException("购置类型不能为空");
        }
        if (farmId == null) {
            throw new OPServerException("养殖场id不能为空");
        }

        Map<String,Object> map = Maps.newHashMap();
        if (farmId != null) {
            map.put("farmId",farmId);
        }
        if (startDate != null) {
            map.put("startDate",startDate);
        }
        if (endDate != null) {
            map.put("endDate",endDate);
        }
        map.put("type",type);
        Map<String,Object> result = farmRecordsPurchaseMapper.selectQuantityByFarmId(map);
        return result;
    }
}
